package com.yc.thread.fairNofairLock;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 测试公平锁和非公平锁
 */
public class ReentrantLockTest {

    // 非公平锁，每次执行都是随机
    private static ReentrantLock nonFairLock = new ReentrantLock();
    // 公平锁，按照第一次循环的顺序执行线程
    private static ReentrantLock fairLock = new ReentrantLock(true);

    public static void main(String[] args) {
        new Thread(() -> test(), "线程1").start();
        new Thread(() -> test(), "线程2").start();
        new Thread(() -> test(), "线程3").start();
        new Thread(() -> test(), "线程4").start();
        new Thread(() -> test(), "线程5").start();
    }

    public static void test() {
        for (int i=0; i < 2; i++) {
            nonFairLock.lock();
            System.out.println(Thread.currentThread().getName() + "获取了锁");
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                nonFairLock.unlock();
            }
        }
    }
}
